package cn.dansj.handler.interfaces;

import cn.dansj.annotation.InterfaceParam;
import cn.dansj.annotation.MarkAsApi;
import cn.dansj.entity.User;
import cn.dansj.common.utils.enums.ResponseCode;
import cn.dansj.exception.InterfaceResponseException;
import cn.dansj.service.UserService;
import cn.dansj.common.context.ApplicationContextProvider;
import cn.dansj.common.request.RequestUtils;
import cn.dansj.handler.InterfaceHandler;
import cn.dansj.utils.project.ProjectUtils;

import java.util.Map;

@SuppressWarnings("all")
@MarkAsApi
public class H5Login extends InterfaceHandler {

    @Override
    @InterfaceParam(require = true, value = "username", comment = "用户名")
    @InterfaceParam(require = true, value = "password", comment = "验证码")
    @InterfaceParam(require = true, value = "platform", comment = "平台信息")
    public Object execute(Map<String, Object> paramsMap) {
        final Object username = paramsMap.get("username");
        final Object password = paramsMap.get("password");
        final Object platform = paramsMap.get("platform");
        if (username == null) {
            throw new InterfaceResponseException(ResponseCode.AuthenticationFailed.getStatusCode(), "用户名不能为空");
        } else if (password == null) {
            throw new InterfaceResponseException(ResponseCode.AuthenticationFailed.getStatusCode(), "验证码不能为空");
        } else if (platform == null) {
            throw new InterfaceResponseException(ResponseCode.AuthenticationFailed.getStatusCode(), "平台信息不能为空");
        }
        String key = "verificationCode@" + username.toString();
        final String pwd = redisUtils.getString(key);
        final boolean pwdCheckPass = pwd.toLowerCase().equals(password.toString().toLowerCase());
        if (pwdCheckPass) {
            redisUtils.delete(key);
            final UserService userService = ApplicationContextProvider.getBean(UserService.class);
            final User user = userService.getUser(username.toString());
            RequestUtils.getRequest().setAttribute("platform", platform);
            return Map.copyOf((Map) ProjectUtils.initUserLoginData(user).getData());
        }
        throw new InterfaceResponseException(ResponseCode.AuthenticationFailed.getStatusCode(), "验证码错误");
    }
}
